#!/usr/bin/env python
#-*- coding:utf-8 -*-

from django.shortcuts import render
from django.template.context import RequestContext
from plugins import mysql_check
import models
import os
from django.core import serializers
from django.http import HttpResponse,HttpResponseRedirect
import json
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django import forms
from django.http import StreamingHttpResponse

project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))

class UserForm(forms.Form):
    headImg = forms.FileField(
        label=u"请选择文件",
        widget=forms.FileInput(
            attrs={
                # 'class': "form-control",
            }
        ),
    )

def index(request):
    data = models.Device.objects.all().order_by('-special')
    return render(request, 'index.html',{"data": data,},
                  context_instance=RequestContext(request))

def special(request):
    data = models.Device.objects.filter(special=1)
    return render(request, 'special.html', {"data": data,},
                  context_instance=RequestContext(request))
def gmess(request):
    if request.method == "GET":
        userget = models.Message.objects.filter(Device_id__graphid=request.GET.get('modify')).order_by('id','mark')
        srvs_json = serializers.serialize("json", userget)
        mimi = models.Device.objects.filter(graphid=request.GET.get('modify'))
        data = {'mimi':mimi[0].special,'data':json.loads(srvs_json)}
        return HttpResponse(json.dumps(data))


def devlist(request):
    return render(request, 'devlist.html',
                  context_instance=RequestContext(request))
def get_report(request):
    data_list = []
    for i in models.Device.objects.all():
        data = {"graphid": "", "name": ""}
        data['graphid'] = i.graphid
        data['name'] = i.name
        data_list.append(data)
    return HttpResponse(json.dumps({'data': data_list}))

def editdev(request):
    if request.method == "GET":
        contact_list = models.Message.objects.filter(Device_id__graphid=request.GET.get('id')).order_by('id','mark')
        paginator = Paginator(contact_list, 1)
        page = request.GET.get('page')
        try:
            contacts = paginator.page(page)
        except PageNotAnInteger:
            contacts = paginator.page(20)
        except EmptyPage:
            contacts = paginator.page(paginator.num_pages)
        dev = models.Device.objects.get(graphid=request.GET.get('id'))
        uf = UserForm()
        return render(request, 'editdev.html', {'uf':uf,"topics": contacts,"dev":dev},
                      context_instance=RequestContext(request))
    else:
        if request.method == "POST":
            dev = models.Message(mark=request.POST.get('mark'),description=request.POST.get('mess'))
            dev.save()
            grou = models.Device.objects.get(graphid=request.POST.get('id'))
            dev.Device_id.add(grou)
            dev.save()
            return HttpResponseRedirect("/editdev/?id=%s"%request.POST.get('id'))

def deldev(request):
    if request.method == "POST":
        models.Message.objects.get(id=request.POST.get('modify')).delete()
        return HttpResponse(json.dumps('true'))

def deldevall(request):
    if request.method == "POST":
        dev = models.Device.objects.get(id=request.POST.get('modify'))
        models.Message.objects.filter(Device_id__graphid=dev.graphid).delete()
        return HttpResponse(json.dumps('true'))

def inradio(request):
    if request.method == "POST":
        data = models.Device.objects.filter(graphid=request.POST.get('modify'))
        if data[0].special == '1':
            data.update(special=0)
            data.save()
            return HttpResponse(json.dumps('true'))
        else:
            data.update(special=1)
            data.save()
            return HttpResponse(json.dumps('true'))

def download(request):
    def file_iterator(file_name, chunk_size=512):
        with open(file_name) as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
    the_file_name = "导入模板(请不要删除标题行！).csv"
    response = StreamingHttpResponse(file_iterator(os.path.join(project_dir,'upload','moban.csv')))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
    return response

def register(request):
    if request.method == "POST":
        uf = UserForm(request.POST,request.FILES)
        if uf.is_valid():
            #获取表单信息
            headImg = uf.cleaned_data['headImg']
            #写入数据库
            user = models.Download()
            user.headImg = headImg
            user.save()
            with open(os.path.join(project_dir,str(user.headImg)).decode('utf-8'), 'r') as f:
                print u"读取文件结束,开始导入!"
                next(f)  # 将文件标记移到下一行
                y = 0
                for line in f:
                    row = line.replace('"', '')  # 将字典中的"替换空
                    row = row.split(',')  # 按,对字符串进行切片
                    y = y + 1
                    grou = models.Device.objects.get(graphid=request.POST.get('id'))
                    aa = models.Message(mark=str(row[0]), description=row[1].decode('gbk'))
                    aa.save()
                    aa.Device_id.add(grou)
                print "成功导入数据" + str(y) + "条"
            return HttpResponseRedirect("/editdev/?id=%s"%request.POST.get('id'))